﻿using System;
using System.Collections.Generic;
using System.Reflection;
using LinFu.IoC.Configuration;

namespace CoreEx.Database.Linq.Implementation
{
    /// <summary>
    /// Provides an alias for a given <see cref="MemberInfo"/> instance.
    /// </summary>    
    [Implements(typeof(IAliasProvider),LifecycleType.OncePerThread)]
    public class AliasProvider : IAliasProvider
    {
        [ThreadStatic]
        private static readonly IDictionary<MemberInfo, string> 
            _aliasMap = new Dictionary<MemberInfo, string>();

        /// <summary>
        /// Gets an alias based on the supplied <paramref name="member"/>
        /// </summary>
        /// <param name="member">The <see cref="MemberInfo"/> for which to return an alias.</param>
        /// <returns></returns>
        /// <remarks>
        /// If the <paramref name="member"/> represents an existing alias,
        /// a new alias should be created for this member.
        /// </remarks>
        public string GetAliasFor(MemberInfo member)
        {
            if (!_aliasMap.ContainsKey(member))            
                _aliasMap.Add(member, string.Format("t{0}", _aliasMap.Count));
            
            return _aliasMap[member];
        }

        /// <summary>
        /// Resets the <see cref="IAliasProvider"/> and
        /// clears the internal list of used aliases.
        /// </summary>
        public void Reset()
        {
            _aliasMap.Clear();
        }
    }
}
